package tcp;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class TCPServer {
    public static void main(String[] args) throws IOException {
        // 创建一个ServerSocket对象，监听7788端口
        ServerSocket serverSocket = new ServerSocket(7788);
        System.out.println("服务器启动成功");
        while (true) {
            new Thread() {
                @Override
                public void run() {
                    // 等待客户端连接
                    Socket socket = null;
                    try {
                        socket = serverSocket.accept();
                        System.out.println("客户端连接成功");
                        // 向客户端发送欢迎信息
                        socket.getOutputStream().write(("欢迎你" + socket.getPort()).getBytes(StandardCharsets.UTF_8));
                        System.out.println("客户端端口号：" + socket.getPort());
                        // 等待2秒
                        Thread.sleep(2000);
                        // 关闭连接
                        socket.close();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }.start();
        }
    }
}
